from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework import status
import re,random
from django.db.models import Q
from .serial import RegisterSerializer
from .models import UserModel
from DXdjango.utils.RongLianYun import send_message
from django.conf import settings
from django_redis import get_redis_connection
from mycelery.sms.tasks import send_sms
from .serial import CustomTokenObtainPairSerializer
# Create your views here.


# lookup_field = 'pk'
# lookup_url_kwarg = 'courseID'
# lookup_field = 'pk'
#     # lookup_url_kwarg = "courseID"
# def get_object(self):
#         courseID = int(self.kwargs.get('courseID', 0))
#         course = CourseModel.objects.get(id=courseID)
#         return course

class UserRegisterView(CreateAPIView):
    serializer_class = RegisterSerializer
    queryset = UserModel.objects.all()


class CheckPhoneView(APIView):
    def get(self,request, *args, **kwargs):
        phone = self.kwargs.get('phone',None)
        if phone is not None:
            if re.match(r'^1[3-9]\d{9}$', phone):
                user = UserModel.objects.filter(phone=phone).first()
                if not user:
                    return Response({'msg':'手机号可以注册'},status=status.HTTP_200_OK)
                else:
                    return Response({'msg':'用户已存在'},status=status.HTTP_406_NOT_ACCEPTABLE)
            else:
                return Response({'msg':'手机号格式不正确'},status=status.HTTP_406_NOT_ACCEPTABLE)
        else:
            return Response({'msg':'手机号不能为空'},status=status.HTTP_406_NOT_ACCEPTABLE)


class SendSmsCodeView(APIView):
    def get(self,request, *args, **kwargs):
        phone = self.kwargs.get('phone',None)
        redis = get_redis_connection('sms_code')
        res_interval = redis.ttl(f"interval_{phone}")
        if res_interval != -2:
            return Response({'msg':'请稍后再试'},status=status.HTTP_406_NOT_ACCEPTABLE)
        ronglianyun = settings.RONGLIANYUN
        tid = ronglianyun['reg_tid']
        sms_expires = ronglianyun['sms_expire']
        sms_interval = ronglianyun['sms_interval']
        code = f'{random.randint(0,9999):04d}'
        interval = sms_interval / 60
        datas =(code,interval)
        from mycelery.sms.tasks import send_sms
        send_sms.delay(tid,phone,datas)
        pipe = redis.pipeline()
        pipe.multi()
        redis.setex(f"sms_{phone}",sms_expires,code)
        redis.setex(f"interval_{phone}",sms_interval,'1') #储存成字符串
        pipe.execute()
        return Response({'msg':'发送成功'},status=status.HTTP_200_OK)
        # else:
        #     return Response({'msg':'发送失败'},status=status.HTTP_406_NOT_ACCEPTABLE)


class SmsLoginView(APIView):
    def get(self,request,*args,**kwargs):
        phone = self.kwargs.get('phone',None)
        if phone is not None:
            if re.match(r'^1[3-9]\d{9}$', phone):
                user = UserModel.objects.filter(phone=phone).first()
                if user:
                    redis = get_redis_connection('sms_code')
                    ronglianyun = settings.RONGLIANYUN
                    tid = ronglianyun['reg_tid']
                    sms_expires = ronglianyun['sms_expire']
                    sms_interval = ronglianyun['sms_interval']
                    code = f'{random.randint(0, 9999):04d}'
                    interval = sms_interval / 60
                    datas = (code, interval)
                    from mycelery.sms.tasks import send_sms
                    send_sms.delay(tid, phone, datas)
                    pipe = redis.pipeline()
                    pipe.multi()
                    redis.setex(f"sms_{phone}", sms_expires, code)
                    redis.setex(f"interval_{phone}", sms_interval, '1')  # 储存成字符串
                    pipe.execute()
                    return Response({'msg': '发送成功'}, status=status.HTTP_200_OK)
                else:
                    return Response({'msg': '用户不存在'}, status=status.HTTP_406_NOT_ACCEPTABLE)
            else:
                return Response({'msg': '手机号格式不正确'}, status=status.HTTP_406_NOT_ACCEPTABLE)
        else:
            return Response({'msg': '手机号不能为空'}, status=status.HTTP_406_NOT_ACCEPTABLE)

class SmsLogin(APIView):
    def post(self,request):
        phone = request.data.get('phone',None)
        code = request.data.get('code',None)
        redis = get_redis_connection('sms_code')
        interval = redis.ttl(f"interval_{phone}")
        if interval == -2:
            return Response({"msg":'验证码过期'},status=status.HTTP_406_NOT_ACCEPTABLE)
        sms_code = redis.get(f"sms_{phone}")
        if sms_code.decode() != code:
            return Response({"msg":'验证码错误'},status=status.HTTP_406_NOT_ACCEPTABLE)
        user = UserModel.objects.filter(phone=phone).first()
        refresh = CustomTokenObtainPairSerializer.get_token(user)
        pipe = redis.pipeline()
        pipe.multi()
        redis.delete(f"sms_{phone}")
        redis.delete(f"interval_{phone}")
        pipe.execute()
        return Response({'refresh': str(refresh), 'token': str(refresh.access_token),"msg":"登陆成功"},
                        status=status.HTTP_200_OK)













